package com.ee.chat.api.interceptor;

import com.alibaba.fastjson.JSON;
import com.ee.chat.common.bean.Result;
import com.ee.chat.common.util.ConstantsUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 登录拦截
 * @Author Shane
 * @Date 2019/11/21 10:05
 * @param
 * @return
 **/
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Resource(name = "stringRedisTemplate")
    StringRedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getParameter("token");
        String key = ConstantsUtil.USER_TOKEN + token;
        Object userId = redisTemplate.boundHashOps(key).get("userId");
        if(userId == null){
            Result result = Result.returnTokenExpiry();

            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            PrintWriter pw = response.getWriter();
            pw.append(JSON.toJSONString(result));
            pw.close();

            return false;
        }
        return true;
    }
}
